package com.kanshu.ksgb.fastread.doudou.module.download.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;

import com.dl7.recycler.adapter.BaseQuickAdapter;
import com.dl7.recycler.listener.OnRecyclerViewItemClickListener;
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants;
import com.kanshu.ksgb.fastread.doudou.base.baseui.BaseListFragment;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.ReaderInputParams;
import com.kanshu.ksgb.fastread.doudou.common.business.manager.CacheManager;
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVUserManager;
import com.kanshu.ksgb.fastread.doudou.common.business.utils.ReaderJumpConfig;
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseResult;
import com.kanshu.ksgb.fastread.doudou.common.net.bean.PageRequestParams;
import com.kanshu.ksgb.fastread.doudou.common.net.retrofit.RetrofitHelper;
import com.kanshu.ksgb.fastread.doudou.common.net.rx.BaseObserver;
import com.kanshu.ksgb.fastread.doudou.common.util.FileUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.SwipeRefreshHelper;
import com.kanshu.ksgb.fastread.doudou.common.util.Utils;
import com.kanshu.ksgb.fastread.doudou.module.download.activity.DownLoadCenterActivity;
import com.kanshu.ksgb.fastread.doudou.module.download.adapter.DownLoadCenterAdapter;
import com.kanshu.ksgb.fastread.doudou.module.download.bean.SimpleBookInfo;
import com.kanshu.ksgb.fastread.doudou.module.download.event.DeleteDownLoadEvent;
import com.kanshu.ksgb.fastread.doudou.module.download.event.DownloadProgressEvent;
import com.kanshu.ksgb.fastread.doudou.module.download.retrofit.DownloadChapterService;
import com.kanshu.ksgb.fastread.doudou.module.download.service.DownloadBookService;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;

/**
 * Created by xubo on 2018/11/28
 */

public class DownLoadCenterFragment extends BaseListFragment<SimpleBookInfo> implements OnRecyclerViewItemClickListener {

    private List<SimpleBookInfo> mAllList = new ArrayList<>();
    private int mSumDownloadSize;
    // 组内下载的第一章，需要更新刷新一下UI
    private int mGroupfirst = 0;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        getContentAysnc(mRequestParams);
    }

    @Override
    protected BaseQuickAdapter provideAdapter() {
        mAdapter = new DownLoadCenterAdapter(getActivity(), mList);
        mAdapter.setOnItemClickListener(this);
        return mAdapter;
    }

    @Override
    protected void getContentAysnc(PageRequestParams params) {
        RetrofitHelper.getInstance().createService(DownloadChapterService.class)
                .getDownloadBookInfo().compose(asyncRequest())
                .subscribe(new BaseObserver<List<SimpleBookInfo>>(){
            @Override
            public void onResponse(BaseResult<List<SimpleBookInfo>> result, List<SimpleBookInfo> list, Disposable disposable) {
                mAllList.clear();
                if(!Utils.isEmptyList(list)){
                    mAllList.addAll(list);
                }
                settingData();
                SwipeRefreshHelper.swipeRefreshCompleted(mSwipeRefresh, mAdapter);
            }
            @Override
            public void onError(int code, String errDesc) {
                super.onError(code, errDesc);
            }
        });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleDownloadProgressMessage(DownloadProgressEvent event) {
        mGroupfirst += 1;
        if(!Utils.isEmptyList(mAllList) && (event.isGroupFinish || mGroupfirst == 1)) {
            mGroupfirst = event.isGroupFinish ? 0 : mGroupfirst;
            settingData();
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleDeleteDownLoadEvent(DeleteDownLoadEvent event) {
        settingData();
    }


    public void settingData(){
        mList.clear();
        mSumDownloadSize = 0;
        for(SimpleBookInfo item : mAllList){
            String failChapter = MMKVUserManager.getInstance().getDownLoadFailGroupId(item.book_id);
            item.download_count = MMKVUserManager.getInstance().getBookDownloadChapterCount(item.book_id);
            // 本地有缓存章节 或者 有下载任务在队列中 或者有下载失败的章节
            if(item.download_count > 0 || DownloadBookService.isBookIdDownload(item.book_id) || failChapter.length() > 3){
                long downloadSize = CacheManager.getInstance().getBookDownloadSize(item.book_id);
                mSumDownloadSize += downloadSize;
                item.download_size = FileUtils.getFormatSize(downloadSize);
                if(item.download_count == item.chapter_count){
                    // 所有章节都已经下载
                    item.download_state = SimpleBookInfo.STATE_HAS_DOWNLOAD_ALL;
                } else if(TextUtils.equals(DownloadBookService.getCurrentBookId(), item.book_id)){
                    // 存在下载队列中， 且正在下载
                    item.download_state = SimpleBookInfo.STATE_IS_DOWNLOAD;
                } else if(DownloadBookService.isBookIdDownload(item.book_id) && !TextUtils.equals(DownloadBookService.getCurrentBookId(), item.book_id)){
                    // 存在下载队列中， 等待下载中
                    item.download_state = SimpleBookInfo.STATE_WAITING_DOWNLOAD;
                } else {
                    if(failChapter.length() < 3){ // 部分下载成功 无下载失败章节
                        item.download_state = SimpleBookInfo.STATE_PART_DOWNLOAD;
                    } else{
                        item.download_state = SimpleBookInfo.STATE_HAS_DOWNLOAD_FAIL;
                    }
                }
                mList.add(item);
            }
        }
        if(mList.size() > 0) {
            if (mEmptyLayout != null) {
                mEmptyLayout.hide();
            }
            mAdapter.noMoreData();
        }else{
            showEmptyByCode(Constants.ErrCode.NoData);
        }
        mAdapter.notifyDataSetChanged();
        ((DownLoadCenterActivity)getActivity()).setDownloadSize(FileUtils.getFormatSize(mSumDownloadSize));
    }

    public void clearAllDownLoadBook(){
        for(SimpleBookInfo item : mList){
            // 重置书籍下载章节数量
            MMKVUserManager.getInstance().saveBookDownloadChapterCount(item.book_id, 0);
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onItemClick(View view, int position) {
        if(mList.size() > position) {
            ReaderInputParams params = new ReaderInputParams();
            params.book_id = mList.get(position).book_id;
            ReaderJumpConfig.startReaderActivity(getActivity(), params);
        }
    }
}
